<template>
    <div>
        <!-- 搜索栏 -->
        <empSearch :sou="sou" :options="options" :options1="options1" :city="city" :query="query"></empSearch>

        <div class="btn">

            <el-button type="primary" @click="add()">新增毕业生</el-button>
            <el-button type="primary" @click="delAll">批量删除</el-button>
            <el-button type="primary" @click="dialogVisibledao = true">学生批量导入</el-button>
            <el-dialog v-model="dialogVisibledao" title="学生批量导入" width="500">
                <el-upload class="upload-demo" drag action="#" multiple :http-request="handlestudent">
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <template #tip>
                        <div class="el-upload__tip">
                            Drop file here or <em>click to upload</em>
                        </div>
                    </template>
                    <template #footer>
                        <el-button type="primary" @click="confirm">确认</el-button>
                        <el-button type="primary" @click="dialogVisible = false">取消</el-button>

                    </template>
                </el-upload>
            </el-dialog>

            <el-button type="primary" @click="daochu">学生信息导出</el-button>
        </div>


        <!-- 弹窗 -->
        <empDialog :dialogVisible="dialogVisible" :form="form" :title="title" @submit="submit" @qux="qux" @Colse="dialogVisible=$event"></empDialog>

        <!-- table -->
        <empTable :ftab="pgData" @deltab="del" @delall="xuan" @look="look" @edit="edit"></empTable>

        <!-- 分页 -->
        <el-pagination :page-size="pageSize"  layout="prev, pager, next" :total="tableData.length"
            :current-page="currentPage" @current-change="currentChange"  @size-change="handleSizeChange"/>
    </div>


</template>

<script lang="ts" setup>
import empTable from '../../components/empTable.vue';
import empSearch from '../../components/empSearch.vue';
import empDialog from '../../components/empDialog.vue';
// import download from 'downloadjs'
import qs from 'qs'
import * as XLSX from 'xlsx'
import citydata from '../../data/CityData.json'
import { SmileOutlined, DownOutlined } from '@ant-design/icons-vue';
import { getstudents, getaddstudents, getdel, getedit, getdaoru } from '../../request/api';
import { ref, reactive, onMounted, computed ,watch} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import type { Action } from 'element-plus'
import { Item } from 'ant-design-vue/es/menu';
import type { UploadProps, UploadUserFile } from 'element-plus'
import { Form } from 'ant-design-vue';
import axios from 'axios';


interface Soutype {
    stuName: string;
    origin: string;
    collegeId: number | null;
    workCity: string

}

// const props = {
//   expandTrigger: 'hover' as const,
// }

const handleChange = (value) => {
    console.log(value)
}
// 上传
const showCode = ref(false)
const dialogVisibledao = ref(false)
const handlestudent = (file) => {
    console.log(file.file)
    let formDate = new FormData()
    formDate.append('excelFile', file.file)
    formDate.append('code', '1100')
    getdaoru(formDate).then(res => {
        console.log(res)
        if (res.data.code == 200) {
            ElMessage.success('导入成功')
            showCode.value = true
            dialogVisibledao.value = false
            list()
        } else {
            ElMessage.error('导入失败')
        }
    })
}
const confirm = () => {
    if (showCode.value == false) {
        ElMessage.error('请先导入数据')
        return
    } else {
        dialogVisibledao.value = false
    }
}


// 导出
// const daochu = () => {
//     const table = selection.value.$el;
//     const wb = XLSX.utils.table_to_book(table, { sheet: "Sheet1" });
//     XLSX.writeFile(wb, 'table_data.xlsx');
// }
const daochu = () => {
    const link = document.createElement('a');
    link.style.display = 'none';
    link.href =
        'http://localhost:3002/v1.0/api/export/students?' +
        qs.stringify(selection.value);
    link.setAttribute('download', '学生信息表.xlsx');
    document.documentElement.appendChild(link);
    link.click();
}


const tableData = ref([])

// 市场部
const options = [
    {
        value: 0,
        label: '请选择',
    },
    {
        value: '豫中市场部',
        label: '豫中市场部',
    },
    {
        value: '冀北市场部',
        label: '冀北市场部',
    },
    {
        value: '鲁冀市场部',
        label: '鲁冀市场部',
    },
    {
        value: '辽东市场部',
        label: '辽东市场部',
    },
    {
        value: '辽宁市场部',
        label: '辽宁市场部',
    },
    {
        value: '中原市场部',
        label: '中原市场部',
    },
    {
        value: '黑北市场部',
        label: '黑北市场部',
    },
    {
        value: '山东市场部',
        label: '山东市场部',
    },
    {
        value: '晋中市场部',
        label: '晋中市场部',
    },
    {
        value: '邯郸市场部',
        label: '邯郸市场部',
    }
]
// 学院
const options1 = [
    {
        value: 0,
        label: '请选择',

    },
    {
        value: 1,
        label: '游戏学院',
    },
    {
        value: 2,
        label: '网站工程学院',
    }
]


const list = () => {
    getstudents().then(res => {
        // console.log(res,'students1')
        tableData.value = res.data.data.result.map((item: any, index: number) => {
            if (item.status == '1') {
                item.status = '未毕业'
            } else if (item.status === '2') {
                item.status = '返校重听'
            } else if (item.status === '3') {
                item.status = '已就业'
            } else if (item.status == '4') {
                item.status = '返回未就业'
            } else if (item.status == '5') {
                item.status = '以往未就业'
            }
            return item
        })
        // console.log(tableData.value, 'students')
    })
}

onMounted(() => {
    // 获取数据列表
    list()
    // feny
    fetchData(currentPage.value, pageSize.value)
})


// 搜索
const sou = reactive<Soutype>({
    stuName: '',
    origin: '',
    collegeId: null,
    workCity: ''
})
const query = () => {
    console.log('sss', sou)
    for (const key in sou) {
        if (!sou[key]) {
            delete sou[key]
        }
    }
    getstudents(sou).then(res => {
        tableData.value = res.data.data.result
    })
}


// 分页
const pageSize=ref(5)
const currentPage=ref(1)
const pgData=ref([])

// const pgData = computed(() => {
//     const start = (currentPage.value - 1) * pageSize.value;
//     const end = start + pageSize.value;
//     return tableData.value.slice(start, end)
// })

// axios.get('/api/v1.0/api/student/list', { params: { limit: 5, skip: 1 } }).then(res => {
//     console.log(res, 'res123')
//     pgData.value=res.data.data.result
// })
const fetchData = async (page:any, size:any) => {
  try {
    const response = await axios.get('/api/v1.0/api/student/list', {
      params: {
        limit: size,
        skip: (page - 1) * size
      }
    });
    pgData.value = response.data.data.result; // 更新分页数据
    // totalItems.value = response.data.data.total; // 更新总项数
  } catch (error) {
    console.error('Failed to fetch data:', error);
  }
};
// 监听 currentPage 和 pageSize 的变化。
watch([currentPage, pageSize], () => {
  fetchData(currentPage.value, pageSize.value);
}, { immediate: true });
// 页码变化
const currentChange = (page: any) => {
 currentPage.value=page
}
// 处理每页项数变化
const handleSizeChange = (size:any) => {
  pageSize.value = size;
  currentPage.value = 1; // 每次更改每页项数时，重置到第1页
};


// 城市
function transformJsonKeys(data) {
    if (Array.isArray(data)) {
        return data.map(item => transformJsonKeys(item));
    } else if (typeof data === 'object' && data !== null) {
        const newObj = {};
        for (const key in data) {
            if (key === 'code') {
                newObj['value'] = data[key];
            } else {
                newObj[key] = transformJsonKeys(data[key]);
            }
        }
        return newObj;
    }
    return data;
}
const city = transformJsonKeys(citydata)
console.log(city, 'cccccc')


const handleClose = (done: () => void) => {
    //   ElMessageBox.confirm('Are you sure to close this dialog?')
    //     .then(() => {
    //       done()
    //     })
    //     .catch(() => {
    //       // catch error
    //     })
}



// 多选
const selection = ref(false)
const delData = ref(false)

 // 选择
// const ids=ref([])
// const xuan = (val: any) => {
//     console.log(val, '22223')
//     let ids = val.map((item: any, index: number) => {
//         return item.id
//     })
//     delData.value = ids
//     console.log([...ftab])
// }
const selectedIds = ref<number[]>([]); // 存储选择的ID
const xuan = (ids: number[]) => {
  selectedIds.value = ids;
};

// 批量删

const delAll = (val: any) => {
    let ids = delData.value
    console.log(val, 'ids99')
    getdel(ids).then(res => {
        console.log(res, 'delall')
        ElMessage.success('批量删成功')
        getstudents().then(res => {
            tableData.value = res.data.data.result
        })
    })
}



interface Form {
    stuName: string;
    className: string;
    collegeId?: number | null;
    expertiseId?: number | null;
    collegeName?: string;
    expertiseName?: string;
    stuNo: string;
    id: number;
    idd?: number;
    origin: string;
    status?: string;
}


const title = ref('添加');

// 弹窗
const dialogVisible = ref(false)
const formLabelWidth = "100px";
const formdisabled = ref(false)
const form = reactive<Form>({
    stuName: "",
    className: "",
    stuNo: "",
    collegeId: null,
    expertiseId: null,
    collegeName: '',
    expertiseName: '',
    id: 0,
    origin: '',
    status: ''

});
// 查看
const look = (row: Form) => {
    title.value = '查看'
    dialogVisible.value = true;
    // 数据回显
    form.className = row.className;
    form.stuName = row.stuName;
    form.stuNo = row.stuNo;
    switch (row.collegeName) {
        case '网站工程学院':
            form.collegeId = 2
            break
        case '游戏学院':
            form.collegeId = 1
            break

        default:
            break
    }
    switch (row.expertiseName) {
        case '游戏设计':
            form.expertiseId = 2
            break
        case '游戏开发':
            form.expertiseId = 1
            break
        case '元宇宙':
            form.expertiseId = 3
            break

        default:
            break
    }
    form.origin = row.origin;

    switch (row.status) {
        case '未毕业':
            form.status = '1'
            break
        case '返校重听':
            form.status = '2'
            break
        case '已就业':
            form.status = '3'
            break
        case '返回未就业':
            form.status = '4'
            break
        case '以往未就业':
            form.status = '5'
            break

        default:
            break
    }
    // 表单禁用
    formdisabled.value = true
}
// 添加
const add = () => {
    title.value = '添加'
    dialogVisible.value = true;
    // form.id=Math.floor(Math.random() * 9000);
    form.className = '';
    form.stuName = '';
    form.stuNo = '';
    form.collegeId = null;
    form.expertiseId = null;
    form.origin = '';
    form.status = '';
    formdisabled.value = false
}

let idd = ref(null)
// 修改
const edit = (row: Form) => {
    form.idd = row.id
    title.value = '编辑'
    dialogVisible.value = true;
    console.log(row)
    form.className = row.className;
    form.stuName = row.stuName;
    form.stuNo = row.stuNo;
    switch (row.collegeName) {
        case '网站工程学院':
            form.collegeId = 2
            break
        case '游戏学院':
            form.collegeId = 1
            break

        default:
            break
    }
    switch (row.expertiseName) {
        case '游戏设计':
            form.expertiseId = 2
            break
        case '游戏开发':
            form.expertiseId = 1
            break
        case '元宇宙':
            form.expertiseId = 3
            break

        default:
            break
    }

    form.origin = row.origin;
    switch (row.status) {
        case '未毕业':
            form.status = '1'
            break
        case '返校重听':
            form.status = '2'
            break
        case '已就业':
            form.status = '3'
            break
        case '返回未就业':
            form.status = '4'
            break
        case '以往未就业':
            form.status = '5'
            break

        default:
            break
    }
    formdisabled.value = false
}
const submit = () => {
    console.log(form, 'form')
    // 这里可以提交数据
    // ElMessage.success("提交成功");
    dialogVisible.value = false;
    if (title.value == '添加') {
        getaddstudents({
            // id:form.id,
            stuName: form.stuName,
            className: form.className,
            stuNo: form.stuNo,
            collegeId: form.collegeId,
            expertiseId: form.expertiseId,
            origin: form.origin,
            status: form.status
        }).then(res => {
            console.log(res, 'addstudents')
            if (res.data.code == 200) {
                ElMessage.success("添加成功");
                getstudents().then(res => {
                    tableData.value = res.data.data.result
                })
            } else {
                ElMessage.error('添加失败');
            }
        })
    } else if (title.value == '编辑') {
        getedit({
            id: form.idd,
            stuName: form.stuName,
            className: form.className,
            stuNo: form.stuNo,
            collegeId: form.collegeId,
            expertiseId: form.expertiseId,
            origin: form.origin,
            status: form.status
        }).then(res => {
            console.log(res, 'edit')
            if (res.data.code == 200) {
                ElMessage.success("编辑成功");
                getstudents().then(res => {
                    tableData.value = res.data.data.result
                })
            }
        })
    } else if (title.value == '查看') {
        console.log('查看')
    }

}
const qux = () => {
    dialogVisible.value = false;
}
// 删除
const del = (val: any) => {
    console.log(val)
    getdel(val).then(res => {
        console.log(res, 'del')
        getstudents().then(res => {
            tableData.value = res.data.data.result
        })
        ElMessage.success("删除成功");
    })

}


</script>

<style lang="scss" scoped>
.btn {
    margin-bottom: 10px;
}
</style>